package cn.com.surker.pages;

import cn.com.surker.common.AbstractController;
import cn.com.surker.oauth.AuthUtils;
import cn.com.surker.platform.PlatformService;
import cn.com.surker.redis.RedisUtils;
import cn.com.surker.spring.RestResultDto;
import cn.com.surker.system.entity.SysUser;
import cn.com.surker.system.model.CacheUser;
import cn.com.surker.system.service.StationLogService;
import cn.com.surker.system.service.UserService;
import cn.com.surker.util.IpUtils;
import cn.com.surker.util.StringUtils;
import cn.com.surker.wechat.WechatAppletApi;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author lucky
 * @create 2022年01月18 9:27
 * @desc 微信小程序
 */
@Controller
public class WechatAppletController extends AbstractController {

    /**用户业务类**/
    @Reference
    private UserService userService;
    /**redis缓存工具**/
    @Resource
    private RedisUtils redisUtils;
    @Reference
    private StationLogService logService;
    @Resource
    private PlatformService platformService;

    /**
     * 小程序手机号授权登录
     * @return
     */
    @RequestMapping(value = "/applet/login")
    @ResponseBody
    public RestResultDto appletLogin(String openCode, String phoneCode, HttpServletRequest request) {
        try {
            if (StringUtils.isNull(openCode) && StringUtils.isNull(phoneCode))
                return RestResultDto.fail("参数错误");

            if (!StringUtils.isNull(phoneCode)) {
                /**手机授权登录**/
                Map<String, Object> map = WechatAppletApi.getPhone(phoneCode);

                if (map == null)
                    return RestResultDto.fail("获取手机号异常");

                String phone = StringUtils.convertString(map.get("phoneNumber"));

                if (StringUtils.isNull(phone))
                    return RestResultDto.fail("获取手机号异常");

                map = new HashMap<>();
                map.put("phone", phone);
                SysUser user = userService.queryUser(phone);
                if (user != null) {
                    CacheUser cacheUser = new CacheUser(user);
                    cacheUser.setRoleList(roleService.loadUserMenu(user.getId()));
                    cacheUser.setRoleNameList(roleService.loadRoleName(cacheUser.getId()));
                    cacheUser.setIp(IpUtils.getIpAddress(request));
                    cacheUser = logService.save(cacheUser);
                    /**加密令牌**/
                    String appToken = AuthUtils.createToken(cacheUser.getId() + new Date().getTime());
                    cacheUser.setToken(appToken);
                    redisUtils.set(appToken, cacheUser, 7200L);
                    AbstractController.setUserCookie(cacheUser);
                    map.put("token", getUser().getToken());
                }

                return RestResultDto.success(map);
            } else if (!StringUtils.isNull(openCode)) {
                /**openid授权登录**/
                Map<String, Object> map = WechatAppletApi.getCodeSession(openCode);
                String openid = StringUtils.convertString(map.get("openid"));
                if (StringUtils.isNull("openid"))
                    return RestResultDto.fail("获取openid异常");

                SysUser user = userService.queryUser(openid);
                if (user != null) {
                    CacheUser cacheUser = new CacheUser(user);
                    cacheUser.setRoleList(roleService.loadUserMenu(user.getId()));
                    cacheUser.setRoleNameList(roleService.loadRoleName(cacheUser.getId()));
                    cacheUser.setIp(IpUtils.getIpAddress(request));
                    cacheUser = logService.save(cacheUser);
                    /**加密令牌**/
                    String appToken = AuthUtils.createToken(cacheUser.getId() + new Date().getTime());
                    cacheUser.setToken(appToken);
                    redisUtils.set(appToken, cacheUser, 7200L);
                    AbstractController.setUserCookie(cacheUser);
                    map.put("token", getUser().getToken());
                } else {
                    Integer type = platformService.queryPlatformType(StringUtils.convertString(map.get("openid")));
                    if (type != -1) {
                        map.put("redirectType", type);//跳转类型
                    }
                }
                return RestResultDto.success(map);
            }

            return RestResultDto.fail("获取用户信息失败");
        } catch (Exception e) {
            e.printStackTrace();
            return RestResultDto.fail("系统异常,加载数据失败");
        }

    }

    /**
     * 小程序更新用户信息
     * @return
     */
    @RequestMapping(value = "/applet/update")
    @ResponseBody
    public RestResultDto appletUpdate(String openid, String unionid, String phone, String sessionKey) {
        try {
            if (StringUtils.isNull(openid) && StringUtils.isNull(phone))
                return RestResultDto.fail("参数错误");

            return RestResultDto.complete(userService.update(openid, unionid, phone, sessionKey));
        } catch (Exception e) {
            e.printStackTrace();
            return RestResultDto.fail("系统异常,加载数据失败");
        }


    }

    /**
     * 微信小程序首页
     * @return
     */
    @RequestMapping("/wechat/login")
    public ModelAndView wechatLogin(String phone, String token, String openid, String avatarUrl, String nickName) {
        if (!StringUtils.isNull(phone) && !StringUtils.isNull(token)) {
            if (redisUtils.exists(token)) {
                CacheUser user = (CacheUser) redisUtils.get(token);
                if (user != null) {
                    if (user.getPhone().equals(phone)) {
                        /**将登录token存入session**/
                        ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                                .getSession().setAttribute("oauth_token", token);

                        ModelAndView modelAndView = new ModelAndView("cloud/index");
                        return modelAndView;
                    }
                }
            }
        } else if (!StringUtils.isNull(token) && !StringUtils.isNull(openid)) {
            if (redisUtils.exists(token)) {
                CacheUser user = (CacheUser) redisUtils.get(token);
                if (user != null) {
                    if (user.getOpenid().equals(openid)) {
                        /**将登录token存入session**/
                        ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                                .getSession().setAttribute("oauth_token", token);
                        ModelAndView modelAndView = new ModelAndView("cloud/index");
                        return modelAndView;
                    }
                }
            }
        }
        ModelAndView modelAndView = new ModelAndView("cloud/wechat-login");
        modelAndView.addObject("avatarUrl", avatarUrl);
        modelAndView.addObject("nickName", nickName);
        modelAndView.addObject("openid", openid);
        return modelAndView;
    }
    /**
     * 默认首页
     * @return
     */
    @RequestMapping("/")
    public String index() {
        return "cloud/login";
    }

}
